
qsi = read.csv('data/qsi_publicuse_2020v1.csv', 
               header = T) %>% 
  mutate(law_justice =  as.numeric(Law  == 1 |  Justice  == 1 | Policing == 1, 1,0)) %>% 
  group_by(Location) %>% 
  summarise(law_justice = mean(law_justice, na.rm = T), 
            law_justice = as.numeric(law_justice > 0 , 1,0)
            )
qsi$ccode = countrycode::countrycode(qsi$Location, 'country.name', 'cown')
qsi$ccode = ifelse(qsi$ccode == 817, 816, qsi$ccode)

data("World")

World$ccode = countrycode::countrycode(World$iso_a3, 'iso3c', 'cown')
World = merge(qsi, World, by = 'ccode', all.y = T)
World = World %>% 
  filter(continent != 'Antarctica')
World = st_as_sf(World)
World$law_justice[is.na(World$ccode)] = NA 

World$law_justice = as.numeric(World$law_justice)
World$law_justice[is.na(World$law_justice)] = 'Nope'
World$law_justice = as.factor(World$law_justice)

world_no_court = World |> 
  filter(law_justice == 'Nope') 
world_court = World |> 
  filter(law_justice != 'Nope') 

world_map = tm_shape(world_no_court) + tm_borders(lwd = .001) +
  tm_shape(world_court) + tm_borders(lwd = 2) + 
                                tm_fill('law_justice', 
                                  title  = 'Rebel Law & Courts?', 
                                  labels = c("No", "Yes", 'No Civil War'), 
                                  palette = c('grey', 'black', 'white')) + 
  tm_layout(frame = FALSE) + 
  tm_layout(frame = FALSE, legend.position = c('left', 'bottom'))

world_map = tm_shape(World) + tm_fill('law_justice', 
                          title  = 'Rebel Law & Courts?', 
                          labels = c("No", "Yes", 'No Civil War'), 
                          palette = c('grey', 'black', 'white')
                          ) + 
  tm_shape(World) + tm_borders() + 
  tm_layout(frame = FALSE, legend.position = c('left', 'bottom'))

tmap_save(world_map, 'fig-out/world_map.pdf')
